import { createStore } from 'vuex'
import { getinfo,login,sidemenu } from '~/api/admin/manager.js'
import { setToken,removeToken } from '~/composables/auth.js'

// 创建一个新的 store 实例
const store = createStore({
  state () {
   return{
    //用户信息
    user:{},
    //侧边宽度
    asideWidth : "250px",
    //侧边栏按钮
    menus : [],
    //权限
    ruleNames : [],
   }
  },
  mutations: {
    //记录用户相关信息
    SET_USERINFIFO(state,user){
      state.user = user
    },
    //展开-缩起侧边宽度
    handelAsideWidth(state){
      state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
    },
    SET_MENUS(state,menus){
      state.menus = menus
    },
    SET_RULENAMES(state,ruleNames){
      state.ruleNames = ruleNames
    },
  },
  actions:{
    //登录方法（来自登录页）
    login({ commit },{ username,password}){
      return new Promise((resolve,reject)=>{
        login(username,password)
        .then(res=>{
          //console.log(res);
          //存储token
          setToken(res.data.token)

          resolve(res)
        }).catch(err=>reject(err))
      })
    },
    //获取当前登录用户信息
    getinfo({ commit }){
      return new Promise((resolve,reject)=>{
        getinfo()
        .then(res=>{
          //console.log(res);
          commit('SET_USERINFIFO',res.data)
          commit("SET_MENUS",res.data.menu)
          
          resolve(res)
        }).catch(err=>reject(err))
        //获取侧边栏按钮
        /* sidemenu()
        .then(res2=>{
          commit("SET_MENUS",res2.data)
          resolve(res2)
        }).catch(err=>reject(err)) */
      })
    },
    
    
    //退出登录
    logout({ commit }){
      removeToken()

      commit('SET_USERINFIFO',{})
    }
  }
})

export default store